package com.baidu.lib_home.adapter

import android.util.Log
import androidx.recyclerview.widget.RecyclerView
import com.baidu.lib_audio.AudioController
import com.baidu.lib_audio.AudioHelper
import com.baidu.lib_audio.R
import com.baidu.lib_common.base.BaseRecyclerViewAdapter
import com.baidu.lib_common.constant.AudioChangeEvent
import com.baidu.lib_common.utils.loadurl
import com.baidu.lib_home.databinding.MusicItemBinding
import com.baidu.lib_leancloud.AudioFavoriteChangeEvent
import com.baidu.lib_leancloud.db.FavoriteViewModel
import com.baidu.lib_leancloud.db.RoomHelper
import com.baidu.lib_leancloud.model.Music
import kotlinx.coroutines.CoroutineScope
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MusicAdapter: BaseRecyclerViewAdapter<MusicItemBinding,Music>() {
    private var recyclerView: RecyclerView? = null
    val favoriteViewModel: FavoriteViewModel = FavoriteViewModel()
    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        this.recyclerView = recyclerView
        EventBus.getDefault().register(this)
    }

    override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
        super.onDetachedFromRecyclerView(recyclerView)
        EventBus.getDefault().unregister(this)
    }
    override fun bindData(binding: MusicItemBinding, data: Music) {
        binding.musicImage.loadurl(data.image)
        binding.musicName.text = data.name
        binding.singer.text = data.singer
        binding.root.setOnClickListener{
            AudioController.instance.changePlayMode(false,false)
            EventBus.getDefault().post(AudioChangeEvent(data,getDataList()))
        }
        binding.love.setOnClickListener{
            RoomHelper.sharedFavoriteViewModel!!.changeFavoriteMusic(data.id)
        }
        if(RoomHelper.sharedFavoriteViewModel!!.isFavorite(musicId = data.id)){
            binding.love.setImageResource(com.baidu.lib_common.R.drawable.audio_selected_love)
        }else{
            binding.love.setImageResource(com.baidu.lib_common.R.drawable.audio_love)
        }


    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun AudioFavoriteChangeEvent(event: com.baidu.lib_leancloud.AudioFavoriteChangeEvent){
        // 1. 找到音乐在列表中的位置
        val position = getDataList().indexOfFirst { it.id.equals(event.music.musicId) }
        if (position == -1) return

        // 2. 获取对应位置的ViewHolder
        val viewHolder = recyclerView?.findViewHolderForAdapterPosition(position) as? MyViewHolder<MusicItemBinding>
        if(viewHolder == null)return
        val favoriteView = viewHolder.binding.love
        if(event.isFavorite){
            favoriteView.setImageResource(com.baidu.lib_common.R.drawable.audio_selected_love)
        }else{
            favoriteView.setImageResource(com.baidu.lib_common.R.drawable.audio_love)
        }
    }
}